import cloud from '@lafjs/cloud'
const db = cloud.mongo.db

export default async function (ctx: FunctionContext) {
  let data = ctx.body

  let whereJson = {}
  let withinScopeOrders = []

  //如果有时间筛选
  if (data.year) {
    //传入年份的start和end内
    const startOfYear = new Date(data.year, 0, 1).getTime(); // 该年份的开始时间戳
    const endOfYear = new Date(data.year, 11, 31, 23, 59, 59, 999).getTime(); // 该年份的结束时间戳

    //判断是否有挪至次年的标记，有的话是否等于传入的年份
    let aa = await db.collection("web-order").find({
      statisticsYear: {
        $exists: true,   // 判断属性存在[1,2](@ref)
        $eq: data.year        // 验证值等于2025[5](@ref)
      }
    }).project({ _id: 1 }).toArray()

    //没有标记，正常筛选
    let timeobj = {
      _add_time: { $gte: startOfYear, $lt: endOfYear },
      statisticsYear: { $exists: false }
    }
    let bb = await db.collection("web-order").find(timeobj).project({ _id: 1 }).toArray()

    let cc = [...aa, ...bb]
    cc.forEach(element => {
      withinScopeOrders.push(element._id)
    });

    whereJson["_id"] = { $in: withinScopeOrders } //特定的订单id
  }

  //订单自带的课程筛选
  if (data.curriculum_id && data.curriculum_id.length) whereJson["curriculum_id"] = { $in: data.curriculum_id }

  let res = await db.collection("web-course").find({}).project({ name: 1 }).toArray()

  let aa = await db.collection("moxueyuan-order-list").find(whereJson).project({ curriculum_id: 1, user_detail_info: 1 }).toArray()
  aa.forEach(element => {
    let index = cloud.utils.findIndexByField(res, "_id", element.curriculum_id)
    if (index != -1) element.curriculum_name = res[index].name
  });

  return cloud.utils.requestReturn({ data: countAccountsByStatus(aa) })
}


function countAccountsByStatus(dataArray) {
  // 用于存储统计结果，以 curriculum_id 为键
  const result = {};

  // 遍历传入的JSON数组 [6,8](@ref)
  dataArray.forEach(item => {
    const curriculumId = item.curriculum_id;
    const disabled = item.user_detail_info.disabled;

    // 如果该课程ID还未在结果中，初始化统计对象 [5](@ref)
    if (!result[curriculumId]) {
      result[curriculumId] = {
        curriculum_id: curriculumId,
        curriculum_name: item.curriculum_name,
        total: 0,
        enabled: 0,  // disabled=0 的数量
        disabled: 0  // disabled不为0的数量
      };
    }

    // 更新统计计数
    result[curriculumId].total += 1;

    if (disabled == 0) {
      result[curriculumId].enabled += 1;
    } else {
      result[curriculumId].disabled += 1;
    }
  });

  // 将结果对象转换为数组返回 [7](@ref)
  return Object.values(result);
}